﻿using System;
using MySql.Data.MySqlClient;

namespace DevOnServer
{
    public class CQueryResult : IDisposable
    {
        private MySqlDataReader m_data;

        private bool m_active;

        public CQueryResult(MySqlDataReader rdr)
        {
            m_data = rdr;
            m_active = true;
        }

        public bool advance()
        {
            if (m_active)
                return m_data.Read();
            else
                return false;
        }

        public T read<T>(string column)
        {
            if (!m_active)
                return default(T);
            try
            {
                return typeof(T) == typeof(bool) ? (T)(object)(read<int>(column) != 0) : (T)m_data[column];
            }
            catch (Exception)
            {
                CConsole.WriteLine("MySql query result: failed to convert T {0}, returning default value {1} (column ID: {2} - expected {3})", typeof(T).Name, default(T), column, m_data[column].GetType().Name);
                return default(T);
            }
        }

        public T read<T>(int column)
        {
            if (!m_active)
                return default(T);
            try
            {
                return typeof(T) == typeof(bool) ? (T)(object)(read<int>(column) != 0) : (T)m_data[column];
            }
            catch (Exception)
            {
                CConsole.WriteLine("MySql query result: failed to convert T {0}, returning default value {1} (column ID: {2} - expected {3})", typeof(T).Name, default(T), column, m_data[column].GetType().Name);
                return default(T);
            }
        }

        public void Dispose()
        {
            m_active = false;
            m_data.Close();
            m_data = null;
        }
    }
}